<!DOCTYPE html>
<html lang=zh>
<head><meta name="generator" content="Hexo 3.9.0">
    <!-- so meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="HandheldFriendly" content="True">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="前言拖拽排序是一个很常用的功能，今天就介绍前端和后端分别如何实现。 前端如何实现拖拽排序这里直接使用第三方库—sortable.js，关于它的用法大家可以去参考官方文档 首先我们创建一个表格，这里因为是读取的数据，所以我们使用 JavaScript 动态创建。 index.html123456789&amp;lt;script type=&quot;text/javascript&quot; src=&quot;//unpkg.com">
<meta name="keywords" content="default">
<meta property="og:type" content="article">
<meta property="og:title" content="拖拽排序-sortable.js">
<meta property="og:url" content="https://andyliwr.github.io/2018/12/08/sortable_js/index.html">
<meta property="og:site_name" content="月光倾城的代码小屋">
<meta property="og:description" content="前言拖拽排序是一个很常用的功能，今天就介绍前端和后端分别如何实现。 前端如何实现拖拽排序这里直接使用第三方库—sortable.js，关于它的用法大家可以去参考官方文档 首先我们创建一个表格，这里因为是读取的数据，所以我们使用 JavaScript 动态创建。 index.html123456789&amp;lt;script type=&quot;text/javascript&quot; src=&quot;//unpkg.com">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://img.vim-cn.com/59/d7f8814d0f67906eee5ab7c3e0a2ee00bb2f26.jpg">
<meta property="og:updated_time" content="2018-12-08T14:56:30.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="拖拽排序-sortable.js">
<meta name="twitter:description" content="前言拖拽排序是一个很常用的功能，今天就介绍前端和后端分别如何实现。 前端如何实现拖拽排序这里直接使用第三方库—sortable.js，关于它的用法大家可以去参考官方文档 首先我们创建一个表格，这里因为是读取的数据，所以我们使用 JavaScript 动态创建。 index.html123456789&amp;lt;script type=&quot;text/javascript&quot; src=&quot;//unpkg.com">
<meta name="twitter:image" content="https://img.vim-cn.com/59/d7f8814d0f67906eee5ab7c3e0a2ee00bb2f26.jpg">
    
    
        
          
              <link rel="shortcut icon" href="/images/favicon.ico">
          
        
        
          
            <link rel="icon" type="image/png" href="/images/favicon-192x192.png" sizes="192x192">
          
        
        
          
            <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">
          
        
    
    <!-- title -->
    <title>拖拽排序-sortable.js</title>
    <!-- styles -->
    <link rel="stylesheet" href="/css/style.css">
    <!-- persian styles -->
    
      <link rel="stylesheet" href="/css/rtl.css">
    
    <!-- rss -->
    
    
</head>

<body class="max-width mx-auto px3 ltr">
    
      <div id="header-post">
  <a id="menu-icon" href="#"><i class="fas fa-bars fa-lg"></i></a>
  <a id="menu-icon-tablet" href="#"><i class="fas fa-bars fa-lg"></i></a>
  <a id="top-icon-tablet" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');" style="display:none;"><i class="fas fa-chevron-up fa-lg"></i></a>
  <span id="menu">
    <span id="nav">
      <ul>
         
          <li><a href="/">首页</a></li>
         
          <li><a href="/archives/">归档</a></li>
         
          <li><a href="/search/">搜索</a></li>
         
          <li><a href="/tags/">标签</a></li>
         
          <li><a href="/others/">其他文章</a></li>
        
      </ul>
    </span>
    <br/>
    <span id="actions">
      <ul>
        
        <li><a class="icon" href="/2018/12/08/html5_file_api/"><i class="fas fa-chevron-left" aria-hidden="true" onmouseover="$('#i-prev').toggle();" onmouseout="$('#i-prev').toggle();"></i></a></li>
        
        
        <li><a class="icon" href="/2018/11/27/reuse_python/"><i class="fas fa-chevron-right" aria-hidden="true" onmouseover="$('#i-next').toggle();" onmouseout="$('#i-next').toggle();"></i></a></li>
        
        <li><a class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up" aria-hidden="true" onmouseover="$('#i-top').toggle();" onmouseout="$('#i-top').toggle();"></i></a></li>
        <li><a class="icon" href="#"><i class="fas fa-share-alt" aria-hidden="true" onmouseover="$('#i-share').toggle();" onmouseout="$('#i-share').toggle();" onclick="$('#share').toggle();return false;"></i></a></li>
      </ul>
      <span id="i-prev" class="info" style="display:none;">上一篇</span>
      <span id="i-next" class="info" style="display:none;">下一篇</span>
      <span id="i-top" class="info" style="display:none;">返回顶部</span>
      <span id="i-share" class="info" style="display:none;">分享文章</span>
    </span>
    <br/>
    <div id="share" style="display: none">
      <ul>
  <li><a class="icon" href="http://www.facebook.com/sharer.php?u=https://andyliwr.github.io/2018/12/08/sortable_js/"><i class="fab fa-facebook " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://twitter.com/share?url=https://andyliwr.github.io/2018/12/08/sortable_js/&text=拖拽排序-sortable.js"><i class="fab fa-twitter " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.linkedin.com/shareArticle?url=https://andyliwr.github.io/2018/12/08/sortable_js/&title=拖拽排序-sortable.js"><i class="fab fa-linkedin " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://pinterest.com/pin/create/bookmarklet/?url=https://andyliwr.github.io/2018/12/08/sortable_js/&is_video=false&description=拖拽排序-sortable.js"><i class="fab fa-pinterest " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=拖拽排序-sortable.js&body=Check out this article: https://andyliwr.github.io/2018/12/08/sortable_js/"><i class="fas fa-envelope " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://getpocket.com/save?url=https://andyliwr.github.io/2018/12/08/sortable_js/&title=拖拽排序-sortable.js"><i class="fab fa-get-pocket " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://reddit.com/submit?url=https://andyliwr.github.io/2018/12/08/sortable_js/&title=拖拽排序-sortable.js"><i class="fab fa-reddit " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.stumbleupon.com/submit?url=https://andyliwr.github.io/2018/12/08/sortable_js/&title=拖拽排序-sortable.js"><i class="fab fa-stumbleupon " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://digg.com/submit?url=https://andyliwr.github.io/2018/12/08/sortable_js/&title=拖拽排序-sortable.js"><i class="fab fa-digg " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.tumblr.com/share/link?url=https://andyliwr.github.io/2018/12/08/sortable_js/&name=拖拽排序-sortable.js&description="><i class="fab fa-tumblr " aria-hidden="true"></i></a></li>
</ul>

    </div>
    <div id="toc">
      <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#前言"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#前端如何实现拖拽排序"><span class="toc-number">2.</span> <span class="toc-text">前端如何实现拖拽排序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#后端如何实现排序接口"><span class="toc-number">3.</span> <span class="toc-text">后端如何实现排序接口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#结束"><span class="toc-number">4.</span> <span class="toc-text">结束</span></a></li></ol>
    </div>
  </span>
</div>

    
    <div class="content index py4">
        
        <article class="post" itemscope itemtype="http://schema.org/BlogPosting">
  <header>
    
    <h1 class="posttitle" itemprop="name headline">
        拖拽排序-sortable.js
    </h1>



    <div class="meta">
      <span class="author" itemprop="author" itemscope itemtype="http://schema.org/Person">
        <span itemprop="name">月光倾城的代码小屋</span>
      </span>
      
    <div class="postdate">
        <time datetime="2018-12-08T14:56:30.000Z" itemprop="datePublished">2018-12-08</time>
    </div>


      

      
    <div class="article-tag">
        <i class="fas fa-tag"></i>
        <a class="tag-link" href="/tags/default/">default</a>
    </div>


    </div>
  </header>
  
<div class="article-gallery">
    
    <a class="gallery-item" href="https://img.vim-cn.com/59/d7f8814d0f67906eee5ab7c3e0a2ee00bb2f26.jpg" rel="gallery_ck5exevrk0036ayojd5dnimzj">
        <img src="https://img.vim-cn.com/59/d7f8814d0f67906eee5ab7c3e0a2ee00bb2f26.jpg" itemprop="image" />
    </a>
    
</div>


  <div class="content" itemprop="articleBody">
    <h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>拖拽排序是一个很常用的功能，今天就介绍前端和后端分别如何实现。</p>
<h3 id="前端如何实现拖拽排序"><a href="#前端如何实现拖拽排序" class="headerlink" title="前端如何实现拖拽排序"></a>前端如何实现拖拽排序</h3><p>这里直接使用第三方库—<a href="https://github.com/SortableJS/Sortable" target="_blank" rel="noopener">sortable.js</a>，关于它的用法大家可以去参考官方文档</p>
<p>首先我们创建一个表格，这里因为是读取的数据，所以我们使用 JavaScript 动态创建。</p>
<figure class="highlight html"><figcaption><span>index.html</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span> <span class="attr">src</span>=<span class="string">"//unpkg.com/vue/dist/vue.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span> <span class="attr">src</span>=<span class="string">"//unpkg.com/element-ui@2.3.9/lib/index.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"app"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">el-table</span> <span class="attr">class</span>=<span class="string">"table"</span> <span class="attr">:data</span>=<span class="string">"datas"</span> <span class="attr">:loading</span>=<span class="string">"loading"</span> <span class="attr">border</span> <span class="attr">width</span>=<span class="string">"500px"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">el-table-column</span> <span class="attr">type</span>=<span class="string">"index"</span> <span class="attr">label</span>=<span class="string">"序号"</span> <span class="attr">width</span>=<span class="string">"80"</span> <span class="attr">align</span>=<span class="string">"center"</span>&gt;</span><span class="tag">&lt;/<span class="name">el-table-column</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">el-table-column</span> <span class="attr">prop</span>=<span class="string">"name"</span> <span class="attr">label</span>=<span class="string">"名称"</span> <span class="attr">align</span>=<span class="string">"center"</span>&gt;</span><span class="tag">&lt;/<span class="name">el-table-column</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">el-table-column</span> <span class="attr">prop</span>=<span class="string">"des"</span> <span class="attr">label</span>=<span class="string">"描述"</span> <span class="attr">align</span>=<span class="string">"center"</span>&gt;</span><span class="tag">&lt;/<span class="name">el-table-column</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">el-table</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight scss"><figcaption><span>style.css</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">@import</span> url(<span class="string">'//unpkg.com/element-ui@2.3.9/lib/theme-chalk/index.css'</span>);</span><br><span class="line"><span class="selector-id">#app</span> &#123;</span><br><span class="line">  <span class="attribute">height</span>: <span class="number">300px</span>;</span><br><span class="line">  <span class="attribute">overflow</span>: hidden;</span><br><span class="line">&#125;</span><br><span class="line"><span class="selector-class">.table</span> &#123;</span><br><span class="line">  <span class="attribute">width</span>: <span class="number">500px</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><figcaption><span>app.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> Vue(&#123;</span><br><span class="line">  el: <span class="string">'#app'</span>,</span><br><span class="line">  data: &#123;</span><br><span class="line">    loading: <span class="literal">false</span>,</span><br><span class="line">    datas: [</span><br><span class="line">      &#123;</span><br><span class="line">        name: <span class="string">'栏目1'</span>,</span><br><span class="line">        des: <span class="string">'这是一个测试栏目'</span></span><br><span class="line">      &#125;,</span><br><span class="line">      &#123;</span><br><span class="line">        name: <span class="string">'栏目2'</span>,</span><br><span class="line">        des: <span class="string">'这是一个测试栏目'</span></span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>这样我们就建立了一个很简单的表格，它看上去就是这样：<br><img src="https://file.lantingshucheng.com/2018-12-08-15-35-35.png" alt="简单的表格"></p>
<p>接下来我们使用 sortable.js 让表格变得可拖动，在 vue 的 mounted 方法中初始化需要拖拽的表格（ps: 如果是在 <code>vue</code> 的 <code>created</code> 方法初始化，此时的 dom 没有挂载，会出现 document.querySelector 获取到的 dom 为 null 的情况），</p>
<figure class="highlight js"><figcaption><span>app.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> Vue(&#123;</span><br><span class="line">  <span class="comment">// 省略...</span></span><br><span class="line">  mounted() &#123;</span><br><span class="line">    <span class="keyword">let</span> self = <span class="keyword">this</span>;</span><br><span class="line">    <span class="comment">// 使得表格可以拖拽排序</span></span><br><span class="line">    <span class="keyword">let</span> table = <span class="built_in">document</span>.querySelector(<span class="string">'.el-table__body tbody'</span>);</span><br><span class="line">    Sortable.create(table, &#123;</span><br><span class="line">      forceFallback: <span class="literal">false</span>,</span><br><span class="line">      onEnd(&#123; item, to, <span class="keyword">from</span>, newIndex, oldIndex &#125;) &#123;</span><br><span class="line">        <span class="comment">// 相同位置的交换不发送交换请求</span></span><br><span class="line">        <span class="keyword">if</span> (newIndex == oldIndex) &#123;</span><br><span class="line">          <span class="keyword">return</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="built_in">console</span>.log(newIndex, oldIndex);</span><br><span class="line">          <span class="comment">// 使用ajax将newIndex和oldIndex发送给后端</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>这样表格就变得可以拖动了。值得注意的是如果我们对拖拽元素施加某些限制条件，超过这个条件想取消拖拽操作可以在 <code>onMove</code> 的回调里处理，只要 <code>onMove</code> 返回 <code>false</code>，本次拖拽操作就会被取消掉，元素也会被放置到拖拽前的位置。</p>
<figure class="highlight js"><figcaption><span>app.js</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">Sortable.create(table, &#123;</span><br><span class="line">  forceFallback: <span class="literal">false</span>,</span><br><span class="line">  onMove: <span class="function">(<span class="params">evt, originalEvent</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// 出现非上线和已上线，立即还原交换</span></span><br><span class="line">    <span class="keyword">let</span> draggedIndex = evt.dragged.rowIndex - <span class="number">1</span> &gt;= <span class="number">0</span> ? evt.dragged.rowIndex - <span class="number">1</span> : <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">let</span> relatedIndex = evt.related.rowIndex - <span class="number">1</span> &gt;= <span class="number">0</span> ? evt.related.rowIndex - <span class="number">1</span> : <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> ((self.products[draggedIndex].is_show == <span class="literal">true</span> &amp;&amp; self.products[relatedIndex].is_show == <span class="literal">false</span>) || (self.products[draggedIndex].is_show == <span class="literal">false</span> &amp;&amp; self.products[relatedIndex].is_show == <span class="literal">true</span>) || (self.products[draggedIndex].is_show == <span class="literal">false</span> &amp;&amp; self.products[relatedIndex].is_show == <span class="literal">false</span>)) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  onEnd(&#123; item, to, <span class="keyword">from</span>, newIndex, oldIndex &#125;) &#123;</span><br><span class="line">    <span class="comment">// something</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="后端如何实现排序接口"><a href="#后端如何实现排序接口" class="headerlink" title="后端如何实现排序接口"></a>后端如何实现排序接口</h3><p>假设我们设计表格设计如下，在每行数据中都有一个 priority 属性记录着当前行的排序位置，类似 1,2,3,4….：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">const</span> <span class="string">ThemeSchema</span> <span class="string">=</span> <span class="string">new</span> <span class="string">mongoose.Schema(</span></span><br><span class="line">  <span class="string">&#123;</span></span><br><span class="line">    <span class="attr">priority:</span> <span class="string">Number,</span> <span class="string">//</span> <span class="string">显示优先级</span></span><br><span class="line">    <span class="attr">name:</span> <span class="string">&#123;</span> <span class="attr">type:</span> <span class="string">String,</span> <span class="attr">unique:</span> <span class="literal">true</span> <span class="string">&#125;,</span> <span class="string">//</span> <span class="string">栏目名称</span></span><br><span class="line">    <span class="attr">create_time:</span> <span class="string">Date</span></span><br><span class="line">  <span class="string">&#125;,</span></span><br><span class="line">  <span class="string">&#123;</span> <span class="attr">versionKey:</span> <span class="literal">false</span> <span class="string">&#125;</span></span><br><span class="line"><span class="string">)</span></span><br></pre></td></tr></table></figure>
<p>后端的排序接口的目的其实也就是在接受到前端的排序请求之后修改每行数据的 <code>priority</code> 值，假设我们接受的前端参数分别是 <code>from_index</code> 和 <code>to_index</code>，分别代码的意思是本次拖动排序过程用户将原来排在 from_index 的元素移动到了 to_index 的前面</p>
<p><img src="https://file.lantingshucheng.com/2018-12-08-16-19-38.png" alt="拖动排序示意图1"></p>
<p>所以我们只需要将原来排在 3 位置的元素的 priority 值改成 4，将原来排在 4 位置的元素的 priority 值改成 3，这样就完成了本次排序。<br>当然这样只是跨越一个元素排序，如果 <code>from_index = n</code>，<code>to_index = m</code>，这样就能出现很多种情况：</p>
<ol>
<li><code>n 等于 m</code>，这说明本次是一次无效的拖动排序，直接忽略掉就好了</li>
<li><code>n 小于 m</code>，这说明用户将元素后移了，这样我们需要排序第 n 位的元素的 priority 改成第 m 位元素的前一位(即 m-1 位)的 priority 值，然后将处在 n 到 m 位(区间是 <code>(n, m)</code>,两端的值都不能取 )的元素的 priority 值均减 1 就好了</li>
<li><code>n 大于 m</code>，这说明用户将元素前移了，这样我们需要排序第 n 位的元素的 priority 改成第 m 位元素的 priority 值，然后将处在 m 到 n 位(区间是 <code>[m, n)</code>, 右端的值不能取 )的元素的 priority 值均加 1 就好了</li>
</ol>
<p><img src="https://file.lantingshucheng.com/2018-12-08-16-37-55.png" alt="拖动排序示意图2"></p>
<p>具体代码实现如下：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (!from_index || !to_index) &#123;</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">'invild parameters'</span>)</span><br><span class="line"> <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">if</span> (from_index === to_index) &#123;</span><br><span class="line"> <span class="built_in">console</span>.log(<span class="string">'invild operation'</span>)</span><br><span class="line"> <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> thisTheme = <span class="keyword">await</span> Theme.findOne(&#123; <span class="attr">priority</span>: from_index &#125;, <span class="string">'id priority'</span>)</span><br><span class="line"><span class="keyword">if</span> (from_index &gt; to_index) &#123;</span><br><span class="line">  <span class="keyword">let</span> needChangeTheme = <span class="keyword">await</span> Theme.find(&#123; <span class="attr">priority</span>: &#123; <span class="attr">$lt</span>: from_index, <span class="attr">$gte</span>: to_index &#125; &#125;, <span class="string">'id priority'</span>)</span><br><span class="line">  <span class="keyword">if</span> (thisTheme &amp;&amp; needChangeTheme.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">await</span> Theme.update(&#123; <span class="attr">_id</span>: thisTheme._id &#125;, &#123; <span class="attr">$set</span>: &#123; <span class="attr">priority</span>: to_index &#125; &#125;)</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; needChangeTheme.length; i++) &#123;</span><br><span class="line">      <span class="keyword">await</span> Theme.update(&#123; <span class="attr">_id</span>: needChangeTheme[i]._id &#125;, &#123; <span class="attr">$set</span>: &#123; <span class="attr">priority</span>: needChangeTheme[i].priority + <span class="number">1</span> &#125; &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'exchange success!'</span>)</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'invild parameters'</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  <span class="keyword">let</span> needChangeTheme = <span class="keyword">await</span> Theme.find(&#123; <span class="attr">priority</span>: &#123; <span class="attr">$gt</span>: from_index, <span class="attr">$lte</span>: to_index &#125; &#125;, <span class="string">'id priority'</span>)</span><br><span class="line">  <span class="keyword">if</span> (thisTheme &amp;&amp; needChangeTheme.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">await</span> Theme.update(&#123; <span class="attr">_id</span>: thisTheme._id &#125;, &#123; <span class="attr">$set</span>: &#123; <span class="attr">priority</span>: to_index &#125; &#125;)</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; needChangeTheme.length; i++) &#123;</span><br><span class="line">      <span class="keyword">await</span> Theme.update(&#123; <span class="attr">_id</span>: needChangeTheme[i]._id &#125;, &#123; <span class="attr">$set</span>: &#123; <span class="attr">priority</span>: needChangeTheme[i].priority - <span class="number">1</span> &#125; &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'exchange success!'</span>)</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'invild parameters'</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="结束"><a href="#结束" class="headerlink" title="结束"></a>结束</h3><p>如果你有更好的建议或者困惑的地方，都可以发送邮件到我的邮箱 - <a href="andyliwr@outlook.com">andyliwr@outlook.com</a></p>

  </div>
  <div class="statement">
    <hr>  
    1. 如果本文帮到了您，不妨点一下右上角的”<i class="fas fa-share-alt"></i>“按钮。<br>
    2. 除非注明，本博文章均为原创，转载请以链接形式标明本文地址。<br>
    3. 如果你有任何疑问，欢迎发送邮件到我的邮箱<a href="mailto:andyliwr@outlook.com">andyliwr@outlook.com<br>
  </div>
</article>


    <div class="blog-post-comments">
        <div id="gitalk_thread">
            <noscript>加载评论需要在浏览器启用 JavaScript 脚本支持。</noscript>
        </div>
    </div>



        
          <div id="footer-post-container">
  <div id="footer-post">

    <div id="nav-footer" style="display: none">
      <ul>
         
          <li><a href="/">首页</a></li>
         
          <li><a href="/archives/">归档</a></li>
         
          <li><a href="/search/">搜索</a></li>
         
          <li><a href="/tags/">标签</a></li>
         
          <li><a href="/others/">其他文章</a></li>
        
      </ul>
    </div>

    <div id="toc-footer" style="display: none">
      <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#前言"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#前端如何实现拖拽排序"><span class="toc-number">2.</span> <span class="toc-text">前端如何实现拖拽排序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#后端如何实现排序接口"><span class="toc-number">3.</span> <span class="toc-text">后端如何实现排序接口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#结束"><span class="toc-number">4.</span> <span class="toc-text">结束</span></a></li></ol>
    </div>

    <div id="share-footer" style="display: none">
      <ul>
  <li><a class="icon" href="http://www.facebook.com/sharer.php?u=https://andyliwr.github.io/2018/12/08/sortable_js/"><i class="fab fa-facebook fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://twitter.com/share?url=https://andyliwr.github.io/2018/12/08/sortable_js/&text=拖拽排序-sortable.js"><i class="fab fa-twitter fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.linkedin.com/shareArticle?url=https://andyliwr.github.io/2018/12/08/sortable_js/&title=拖拽排序-sortable.js"><i class="fab fa-linkedin fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://pinterest.com/pin/create/bookmarklet/?url=https://andyliwr.github.io/2018/12/08/sortable_js/&is_video=false&description=拖拽排序-sortable.js"><i class="fab fa-pinterest fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=拖拽排序-sortable.js&body=Check out this article: https://andyliwr.github.io/2018/12/08/sortable_js/"><i class="fas fa-envelope fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://getpocket.com/save?url=https://andyliwr.github.io/2018/12/08/sortable_js/&title=拖拽排序-sortable.js"><i class="fab fa-get-pocket fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://reddit.com/submit?url=https://andyliwr.github.io/2018/12/08/sortable_js/&title=拖拽排序-sortable.js"><i class="fab fa-reddit fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.stumbleupon.com/submit?url=https://andyliwr.github.io/2018/12/08/sortable_js/&title=拖拽排序-sortable.js"><i class="fab fa-stumbleupon fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://digg.com/submit?url=https://andyliwr.github.io/2018/12/08/sortable_js/&title=拖拽排序-sortable.js"><i class="fab fa-digg fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.tumblr.com/share/link?url=https://andyliwr.github.io/2018/12/08/sortable_js/&name=拖拽排序-sortable.js&description="><i class="fab fa-tumblr fa-lg" aria-hidden="true"></i></a></li>
</ul>

    </div>

    <div id="actions-footer">
        <a id="menu" class="icon" href="#" onclick="$('#nav-footer').toggle();return false;"><i class="fas fa-bars fa-lg" aria-hidden="true"></i> 菜单</a>
        <a id="toc" class="icon" href="#" onclick="$('#toc-footer').toggle();return false;"><i class="fas fa-list fa-lg" aria-hidden="true"></i> 目录</a>
        <a id="share" class="icon" href="#" onclick="$('#share-footer').toggle();return false;"><i class="fas fa-share-alt fa-lg" aria-hidden="true"></i> 分享</a>
        <a id="top" style="display:none" class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up fa-lg" aria-hidden="true"></i> 返回顶部</a>
    </div>

  </div>
</div>

        
        <footer id="footer">
  <div class="footer-left">
    Copyright &copy; 2020 Dikang Li
  </div>
  <div class="footer-right">
    <nav>
      <ul>
         
          <li><a href="/">首页</a></li>
         
          <li><a href="/archives/">归档</a></li>
         
          <li><a href="/search/">搜索</a></li>
         
          <li><a href="/tags/">标签</a></li>
         
          <li><a href="/others/">其他文章</a></li>
        
      </ul>
    </nav>
  </div>
</footer>

    </div>
</body>
</html>
<!-- styles -->
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
<link rel="stylesheet" href="/lib/justified-gallery/css/justifiedGallery.min.css">
<link rel="stylesheet" href="/lib/fancybox/jquery.fancybox.css">

<link rel="stylesheet" href="https://file.lantingshucheng.com/blog/v3/static/styles/gitalk.css">


<!-- jquery -->
<script src="/lib/jquery/jquery.min.js"></script>
<script src="/lib/justified-gallery/js/jquery.justifiedGallery.min.js"></script>
<script src="/lib/fancybox/jquery.fancybox.pack.js"></script>

<script type="text/javascript" src="https://file.lantingshucheng.com/blog/v3/static/scripts/md5.js"></script>
<script type="text/javascript" src="https://file.lantingshucheng.com/blog/v3/static/scripts/gitalk.min.js"></script>

<script src="/js/main.js"></script>
<!-- search -->

<!-- Google Analytics -->

<!-- Baidu Analytics -->

    <script type="text/javascript">
        var _hmt = _hmt || [];
        (function() {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?7851ca7a86be957be994acb77639a5be";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
    </script>

<!-- Disqus Comments -->


  <script type="text/javascript">
    window.onload = function(){
      if (window.location.href.indexOf('andyliwr.github.io') > -1) {
        var gitalk = new Gitalk({
          clientID: 'ad6f70df0c70d2b715f9',
          clientSecret: '40384bee244c1e17dd7c37733d21e9ef669e969c',
          repo: 'Andyliwr.github.io',
          owner: 'Andyliwr',
          admin: ['Andyliwr'],
          id: md5(location.pathname),
          distractionFreeMode: 'true'
        })
        gitalk.render('gitalk_thread')
      }
    }
  </script>


